#!/usr/bin/perl

# This script displays a table of all the calibrators we know about, along with their RA, Dec,
# and the latest flux value we have for them, closest to the recommended frequency in each band.

use CGI qw(:standard);
use DBI;
use POSIX;

use strict; use warnings;

my $buffer;

# read in the parameters
$ENV{'REQUEST_METHOD'}=~tr/a-z/A-Z/;
if ($ENV{'REQUEST_METHOD'} eq "GET"){
    $buffer=$ENV{'QUERY_STRING'};
}
# split information into name/value pairs
my @pairs=split(/\&/,$buffer);
my %FORM;
foreach my $pair (@pairs) {
    my ($name,$value)=split(/\=/,$pair);
    $value=~tr/+/ /;
    $value=~s/%(..)/pack("C",hex($1))/eg;
    $FORM{$name}=$value;
}

print header;
print "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">\n";
print "<link rel=\"stylesheet\" type=\"text/css\" href=\"/stylesheets/ca_style.css\">\n";
print "<title>";
print "Information on ".$FORM{'source'};
print "</title></head><body>\n";

# database details
my $dsn="dbi:Pg:dbname=atca;host=mentok;port=5432";
my $user="postgres";
my $password="";

# Setup the database connection
my $dbh=DBI->connect($dsn,$user,$password,{ RaiseError => 0, AutoCommit => 1});

print "<center><h1>Information on ".$FORM{'source'}."</h1></center><br />\n";

print "<h2>General Source Information</h2>\n";

my $gti_query="SELECT calibrators.ra,calibrators.dec,calibrators.type,fluxdata.frequency,".
    "fluxdata.data_freq,fluxdata.tripleamp_value,fluxdata.tripleamp_scatter_measured,".
    "observation.time,fluxdata.closurephase_measured,fluxdata.closurephase_theoretical,".
    "observation.arrayname FROM calibrators,fluxdata,observation WHERE ".
    "calibrators.name=fluxdata.source AND fluxdata.quality_flag=true AND ".
    "observation.id=any(fluxdata.observation_ids) and calibrators.name='".
    $FORM{'source'}."' ORDER BY observation.time DESC";
my $gti=$dbh->prepare($gti_query);
$gti->execute;
my @columns=("ra","dec","type","frequency","data_freq","tripleamp_value",
	     "tripleamp_scatter_measured","time","closurephase_measured",
	     "closurephase_theoretical","arrayname");
my %data_quantities;
while (my @gti_response=$gti->fetchrow){
    for (my $i=0;$i<=$#columns;$i++){
	push @{$data_quantities{$columns[$i]}},$gti_response[$i];
    }
}
$gti->finish;

print "<ul>\n";
my @data_ra=@{$data_quantities{"ra"}};
my @data_dec=@{$data_quantities{"dec"}};
print "<li>RA, Dec: ".$data_ra[0].", ".$data_dec[0]."</li>\n";

print "</ul>\n";

print "<hr />\n";

print "<h2>Calibrator Information</h2>";

my @low_freqs=(0,2000,4000,6500,15000,25000,80000);
my @high_freqs=(2000,4000,6500,10000,25000,55000,110000);
my @bands=("21cm","13cm","6cm","3cm","12mm","7mm","3mm");
my @recfreqs=(1750,2450,5500,9000,17000,19000,33000,35000,44000,46000,93000,95000);

my @data_freq=@{$data_quantities{"frequency"}};
my @data_flux=@{$data_quantities{"tripleamp_value"}};
my @data_fluxunc=@{$data_quantities{"tripleamp_scatter_measured"}};
my @data_times=@{$data_quantities{"time"}};
my @data_closphase_m=@{$data_quantities{"closurephase_measured"}};
my @data_closphase_t=@{$data_quantities{"closurephase_theoretical"}};
my @data_defect;
for (my $i=0;$i<=$#data_closphase_m;$i++){
    my @theseclosphase_ms=@{$data_closphase_m[$i]};
    my @theseclosphase_ts=@{$data_closphase_t[$i]};    
    $data_defect[$i]=$theseclosphase_ms[0]-$theseclosphase_ts[0];
}
my @data_arrayname=@{$data_quantities{"arrayname"}};

print "<center><table border=1 width=\"80%\" cellspacing=0 cellpadding=1 style=\"empty-cells: show\">";
print "<tr valign=middle><th rowspan=2>Wavelength</th><th rowspan=2>Frequency (MHz)</th>".
    "<th rowspan=2>Flux (Jy)</th><th rowspan=2># Obs</th><th rowspan=2>Obs Date</th>".
    "<th colspan=4>Defect</th><th rowspan=2>Extra Info</th></tr>";
print "<tr valign=middle><th>6km</th><th>1.5km</th><th>750m</th><th><375m</th></tr>";
for (my $i=0;$i<=$#low_freqs;$i++){
    my $nfreqs=0;
    my @thesefreqs;
#    for (my $j=0;$j<=$#recfreqs;$j++){
#	if (($recfreqs[$j]>=$low_freqs[$i])&&
#	    ($recfreqs[$j]<$high_freqs[$i])){
#	    $nfreqs++;
#	    push @thesefreqs,$recfreqs[$j];
#	}
#    }
    for (my $j=0;$j<=$#data_freq;$j++){
	if (($data_freq[$j]>=$low_freqs[$i])&&
	    ($data_freq[$j]<$high_freqs[$i])){
	    if ($data_freq[$j]=~/\./){
		# some fractional frequency, we don't like these!
		next;
	    }
	    my $already_added=0;
	    for (my $k=0;$k<=$#thesefreqs;$k++){
		if ($thesefreqs[$k]==$data_freq[$j]){
		    $already_added=1;
		    last;
		}
	    }
	    if ($already_added==0){
		push @thesefreqs,$data_freq[$j];
		$nfreqs++;
	    }
	}
    }
    my @sortedfreqs=sort {$a<=>$b} @thesefreqs;
    @thesefreqs=@sortedfreqs;
    # how many points?
    my @npoints;
    for (my $j=0;$j<=$#data_freq;$j++){
	for (my $k=0;$k<=$#thesefreqs;$k++){
	    if ($thesefreqs[$k]==$data_freq[$j]){
		$npoints[$k]++;
		last;
	    }
	}
    }
    print "<tr align=center><td rowspan=$nfreqs>".$bands[$i]."</td>";
    for (my $j=0;$j<=$#thesefreqs;$j++){
	if ($j!=0){
	    print "<tr align=center>";
	}
	my $stylings="";
	for (my $k=0;$k<=$#recfreqs;$k++){
	    if ($recfreqs[$k]==$thesefreqs[$j]){
		# a recommended frequency
		$stylings=" style=\"background-color: lightgreen\"";
		last;
	    }
	}
	# calculate the defects
	my @def_6km;
	my @def_1500m;
	my @def_750m;
	my @def_375m;
	for (my $k=0;$k<=$#data_freq;$k++){
	    if ($thesefreqs[$j]==$data_freq[$k]){
		if ($data_arrayname[$k]=~/^6.$/){
		    push @def_6km,$data_defect[$k];
		} elsif ($data_arrayname[$k]=~/^1\.5.$/){
		    push @def_1500m,$data_defect[$k];
		} elsif ($data_arrayname[$k]=~/^750.$/){
		    push @def_750m,$data_defect[$k];
		} else {
		    push @def_375m,$data_defect[$k];
		}
	    }
	}
	my $med_def_6km=&median(@def_6km);
	if ($med_def_6km ne " "){
	    $med_def_6km=ceil(abs($med_def_6km))."%";
	}
	my $med_def_1500m=&median(@def_1500m);
	if ($med_def_1500m ne " "){
	    $med_def_1500m=ceil(abs($med_def_1500m))."%";
	}
	my $med_def_750m=&median(@def_750m);
	if ($med_def_750m ne " "){
	    $med_def_750m=ceil(abs($med_def_750m))."%";
	}
	my $med_def_375m=&median(@def_375m);
	if ($med_def_375m ne " "){
	    $med_def_375m=ceil(abs($med_def_375m))."%";
	}
	print "<td$stylings>".$thesefreqs[$j]."</td>";
	for (my $k=0;$k<=$#data_freq;$k++){
	    if ($thesefreqs[$j]==$data_freq[$k]){
		my @thesefluxes=@{$data_flux[$k]};
		my @thesefluxuncs=@{$data_fluxunc[$k]};
		print "<td$stylings>".$thesefluxes[0]." +/- ".$thesefluxuncs[0]."</td>";
		print "<td$stylings>".$npoints[$j]."</td>";
		print "<td$stylings>".$data_times[$k]."</td>";
		# defects
		print "<td$stylings>".$med_def_6km."</td><td$stylings>".$med_def_1500m."</td><td$stylings>".
		    $med_def_750m."</td><td$stylings>".$med_def_375m."</td>";
		print "<td$stylings><a href=\"/cgi-bin/Calibrators/calplot.pl?source=".$FORM{'source'}."&".
		    "freq=".$thesefreqs[$j]."\">".
		    "Flux history</a></td></tr>\n";
		last;
	    }
	}
    }
}

print "</table>\n";

$dbh->disconnect;

print "</body></html>\n";

sub text_to_array {
    my ($text)=@_;
    $text=~s/[\{\}]//g;
    my @els=split(/\,/,$text);
    return @els;
}

sub median {
    my @array=@_;

    my @sorted_array=sort {$a<=>$b} @array;

    my $count=scalar @sorted_array;
    if ($count==0){
	return " ";
    }
    if ($count % 2){
	return $sorted_array[int($count/2)];
    } else {
	return ($sorted_array[$count/2]+$sorted_array[$count/2-1])/2;
    }
}
